import React, { useEffect, useState } from 'react'
import { withRouter } from '@umijs/max'
import zhCN from 'antd-mobile/es/locales/zh-CN'
import { Button, ConfigProvider, theme } from 'antd-mobile'
import { Outlet } from '@umijs/max'
import { history } from 'umi'
import { infraService, accountService } from '@/services'
import { useSearchParams } from '@umijs/max'
import { RedoOutline } from 'antd-mobile-icons'
import { useGlobalStore } from '@/store/global'
import appSettings from '../../config/appSettings'
import { useLocation } from 'umi'
import globalAction from '@/store/globalAction'
import { Msg,ToastContainer } from '@/components/Msg'

function BlankLayout() {
  const [globalErr, setglobalErr] = useState<string>()
  const global = useGlobalStore()

  const [searchParams, setSearchParams] = useSearchParams()

  const turnToUninLogin = () => {
    //登录页
    //获取统一登录地址
    infraService.GetUnitLoginUrl()
      .then((res) => {
        localStorage.setItem('unit_log_url', res)
        //跳转到统一登录页
        const x =
          res +
          `?module_id=${appSettings.moduleId}&redirect_url=${encodeURIComponent(window.location.origin + '/redirect_url')}`
        history.push(x)
      })
      .catch((e) => {
        setglobalErr('获取统一登录地址失败')
      })
  }
  const uniSignInCallback = () => {
    const RefreshToken = searchParams.get('refresh_token') || ''
    const AccessToken = searchParams.get('access_token') || ''

    if (!RefreshToken) {
      setglobalErr('未传入刷新token')
      return
    }
    if (!AccessToken) {
      setglobalErr('未传入访问token')
      return
    }
    sessionStorage.setItem('RefreshToken', RefreshToken)
    sessionStorage.setItem('AccessToken', AccessToken)

    accountService.GetUserInfoByToken()
      .then((res) => {
        Msg.info(`欢迎使用,${res.USERNAME}`)
        global.currUser = res
        setglobalErr(undefined)
        history.push('/sample')
      })
      .catch((e) => {
        setTimeout(() => {
          history.push('/')
        }, 3000)
      })
  }

  const location = useLocation()

  //监听路由变化

  useEffect(() => {
    //杏通回调兼容判断地址中是否存在refresh_token 和 access_token
    const RefreshToken = searchParams.get('refresh_token') || ''
    const AccessToken = searchParams.get('access_token') || ''
    if (AccessToken && RefreshToken) {
      //存在,则直接登录
      uniSignInCallback()
      return
    }
    switch (location.pathname) {
      case '/':
      case '/uni_signin':
        turnToUninLogin()
        break
      case '/redirect_url':
        uniSignInCallback()
        break
      case '/logoff':
        globalAction.onLogoff()
      default:
        break
    }
  }, [location.pathname])

  return (
    <ConfigProvider
      theme={{
        token: {
          borderRadius: 2,
        },
      }}
      button={{ autoInsertSpace: false }}
      locale={zhCN}
    >
      <ToastContainer />
      {(!globalErr && <Outlet />) || (
        <div
          style={{
            color: 'red',
            textAlign: 'center',
            border: '1px red dotted ',
            margin: '55px 10px',
            padding: '15px',
            borderRadius: '10px',
            background: '#ffdfdf',
          }}
        >
          <p style={{ color: '#1f66a7' }}>{appSettings.title}</p>
          <p> {globalErr}</p>
          <p>
            <Button icon={<RedoOutline />} onClick={() => window.location.reload()}>
              刷新
            </Button>
          </p>
        </div>
      )}
    </ConfigProvider>
  )
}

export default withRouter(BlankLayout)
